<template>
  <div v-cloak>
    <el-container>
      <el-main>
        <div class="wf-query">
          <div class="wf-common-title" align="center">
            查询条件
          </div>
          <div style="padding-left: 10px">
            <el-form :inline="true" :model="formInline">
              <el-form-item label="流程名称">
                <el-input v-model="formInline.name" placeholder="请输入..."></el-input>
              </el-form-item>
              <el-form-item label="流程编号">
                <el-input v-model="formInline.key" placeholder="请输入..."></el-input>
              </el-form-item>
              <el-form-item label="激活状态">
                <el-select v-model="formInline.hasHandUp" clearable placeholder="请选择" prop="hasHandUp">
                  <el-option label="请选择" value="-1" :disabled="true"></el-option>
                  <el-option label="未激活" value="true"></el-option>
                  <el-option label="已激活" value="false"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>


        <el-table
          :data="processData"
          style="width: 100%"
          highlight-current-row>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="process-table-expand">
                <el-form-item label="ProcessDefinitionId">
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="DeploymentId">
                  <span>{{ props.row.deploymentId }}</span>
                </el-form-item>
                <el-form-item label="XML文档">
                  <a target="_blank" v-bind:href="xmlUrl(props.row.id)">
                    <span>{{ props.row.xml }}</span>
                  </a>
                </el-form-item>
                <el-form-item label="流程图">
                  <a target="_blank" v-bind:href="imageUrl(props.row.id)">
                    <span>{{ props.row.img }}</span>
                  </a>
                </el-form-item>
                <el-form-item label="操作">
                  <el-button size="mini" type="danger" round
                             @click="deleteDeployment(props.row.deploymentId,props.row.deploymentName)">删除
                  </el-button>
                  <el-button size="mini" type="primary" round @click="convertToModel(props.row.id)">
                    转为Model
                  </el-button>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            prop="name"
            width="300"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            label="KEY"
            prop="key"
            width="200">
          </el-table-column>
          <el-table-column
            label="版本号"
            prop="version">
          </el-table-column>
          <el-table-column
            label="部署时间"
            prop="deploymentDate"
            width="200"
            :formatter="formatter">
          </el-table-column>
          <el-table-column
            label="是否挂起"
            width="150"
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isSuspend">已挂起</el-tag>
              <el-button type="text"
                         @click="updateSuspendState(scope.row.id, scope.row.isSuspend)">
                            <span v-if="scope.row.isSuspend">
                                激活
                            </span>
                <span v-if="!scope.row.isSuspend">
                                挂起
                            </span>
              </el-button>
            </template>

          </el-table-column>
          <el-table-column label="操作" width="260px" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-setting" @click="showNodeDialog(scope.row)">
                节点设置
              </el-button>
              <el-button type="primary" size="mini" icon="el-icon-setting" @click="processSetting(scope.row)">
                流程设置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageable.currentPage"
          :page-sizes="[10, 50, 100]"
          :page-size="pageable.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageable.totalCount"
        >
        </el-pagination>

        <!--流程设置dialog -->
        <el-dialog
          title="流程扩展信息设置"
          :visible.sync="centerDialogVisible"
          center>
          <el-form :model="dialog" :rules="rules" label-position="right" ref="processSetDialog"
                   label-width="150px">
            <el-form-item label="流程名称" prop="name">
              <el-input :disabled="true" v-model="dialog.name"></el-input>
            </el-form-item>
            <el-form-item label="流程编号" prop="key">
              <el-input :disabled="true" v-model="dialog.key"></el-input>
            </el-form-item>
            <el-form-item label="审批类型" prop="approveType" required>
              <el-select v-model="dialog.approveType" placeholder="请选择" prop="approveType">
                <el-option label="请选择" value=""></el-option>
                <el-option
                  v-for="item in approveTypeOption"
                  :key="item.paramValue"
                  :label="item.paramDesc"
                  :value="item.paramValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表单所属系统">
              <el-select v-model="dialog.formServer" placeholder="请选择" @change="qrySysOptionChange">
                <el-option
                  v-for="item in qrySysOptions"
                  :key="item.sysKey"
                  :label="item.sysName"
                  :value="item.sysKey">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审批表单地址" prop="formKey" required>
              <el-input v-model="dialog.formKey" placeholder="请输入表单地址">
                <template slot="prepend">{{dialog.httpHead}}</template>
              </el-input>
            </el-form-item>
            <!--<el-form-item label="自动跳过重复审批人" prop="autoJump" required>-->
            <!--<el-radio v-model="dialog.autoJump" label="true" border>允许</el-radio>-->
            <!--<el-radio v-model="dialog.autoJump" label="false" border>不允许</el-radio>-->
            <!--</el-form-item>-->
          </el-form>
          <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="doSetting('processSetDialog')">确 定</el-button>
                    <el-button @click="doReset('addSysDialog')">重置</el-button>
                </span>
        </el-dialog>

        <!--节点设置dialog -->
        <el-dialog
          title="流程节点信息设置"
          :visible.sync="nodeDialogVisible"
          :fullscreen="true"
          center>
          <el-table
            :data="processNodeList"
            style="width: 100%"
            empty-text=""
            @expand-change=""
            highlight-current-row>

            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table
                  :data="props.row.approverConfigList"
                  style="width: 100%;"
                  header-row-class-name="wf-row-header"
                  v-if="props.row.taskType === 'userTask'"
                >
                  <el-table-column
                    prop="approverType"
                    label="类型"
                    width="300"
                    :show-overflow-tooltip="true"
                    :formatter="approverTypeFormatter">
                  </el-table-column>

                  <el-table-column
                    prop="description"
                    label="审批者描述"
                    width="200"
                  ></el-table-column>

                  <el-table-column
                    prop="value"
                    label="值"
                    width="200"
                  ></el-table-column>

                </el-table>
              </template>
            </el-table-column>

            <el-table-column
              label="任务名称"
              prop="taskName">
            </el-table-column>

            <el-table-column
              label="任务定义编号"
              prop="taskKey">
            </el-table-column>

            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button v-if="scope.row.taskType === 'userTask'" type="text" size="mini"
                           @click="approverSetting(scope.row)">
                  审批人设置
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer" center>
            <el-button @click="nodeDialogVisible = false">关 闭</el-button>
          </div>
        </el-dialog>

        <!-- 设置任务节点审批人-->
        <el-dialog
          title="审批人员设置"
          :visible.sync="approveDialogVisible">
          <el-row>
            <el-col :span="24">
              <el-button-group>
                <el-button icon="el-icon-circle-plus" size="mini" @click="addRole" type="primary">指定角色</el-button>
                <el-button icon="el-icon-circle-plus" size="mini" @click="addUser" type="primary">指定人员</el-button>
                <el-button icon="el-icon-circle-plus" size="mini" @click="addUnit" type="primary">指定部门</el-button>
                <el-button icon="el-icon-circle-plus" size="mini" @click="addUnitLeader" type="primary">部门领导</el-button>
              </el-button-group>
            </el-col>

          </el-row>

          <el-table
            :data="processNodeApproverList"
            style="width: 100%"
            empty-text=""
            @expand-change=""
            highlight-current-row>
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>

            <el-table-column
              prop="approverType"
              label="类型"
              :formatter="approverTypeFormatter">
            </el-table-column>

            <el-table-column
              prop="description"
              label="审批者描述"
              show-overflow-tooltip
            ></el-table-column>

            <el-table-column
              prop="value"
              label="值"
            ></el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.$index, processNodeApproverList)"
                  type="text"
                  size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer" center>
            <el-button @click="approveDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addTaskApprover">保存</el-button>
          </div>
        </el-dialog>

        <chose-role ref="choseRole" @role-choice="roleCallback"></chose-role>
        <chose-user ref="choseUser" @user-choice="userCallBack"></chose-user>
        <chose-unit ref="choseUnit" @unit-choice="unitCallBack"></chose-unit>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import {
    queryProcess,
    deleteProcess,
    updateSuspendState,
    convertToModel,
    loadNode,
    saveTaskApproverSetting,
    loadTaskApproverSetting,
    saveProcessExtendInfo,
    searchProcessExtendInfo
  } from '@/api/process'
  import {formatDate} from '@/utils/index'
  import choseUser from '@/components/ChoseUser'
  import choseRole from '@/components/ChoseRole'
  import choseUnit from '@/components/ChoseUnit'

  const APPROVER_TYPE = {
    ROLE: 'role',
    USER_ID: 'user_id',
    AUTH_POINT: 'auth_point',
    DEPART_LEADER: "depart_leader",
    VICE_PRESIDENT: "vice_president",
    CUSTOM_DEFINE: 'custom_define'
  };

  const APPROVER_TYPE_NAME = {
    "role": '指定角色',
    "user_id": '指定人员',
    "auth_point": '人员矩阵',
    "depart_leader": "部门领导",
    "custom_define": '业务系统自定义'
  };

  const LEADER_TYPE = {
    UNIT_LEADER: 'unit_leader',
    SPECIFIED_UNIT: 'specified_unit_leader'
  };

  export default {
    name: "processManager",
    components: {choseUser, choseRole, choseUnit},
    data() {
      return {
        pageable: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10,
        },
        formInline: {
          name: '',
          key: '',
          hasHandUp: ""
        },
        processData: [],
        centerDialogVisible: false,
        nodeDialogVisible: false,
        dialog: {
          formKey: '',
          name: '',
          key: '',
          httpHead: 'http://127.0.0.1:8080/',
          autoJump: 'false',
          approveType: '',
          boardType: '',
          formServer: ''
        },
        rules: {},
        approveTypeOption: [{
          paramValue: 'rsl',
          paramDesc: '人事类'
        }, {
          paramValue: 'xzl',
          paramDesc: '行政类'
        }
        ],
        boardTypeOption: [],
        processNodeList: [],
        processNodeApproverList: [],
        qrySysOptions: [
          {
            sysKey: '102',
            sysName: '外星探测系统'
          }
        ],
        approveDialogVisible: false,
        selectedProcessKey: '',
        selectedTaskKey: '',
        untilCompanyLeader: false,
        untilVicePresident: false
      }
    },
    methods: {
      loadData(data) {
        queryProcess(data).then(response => {
          this.processData = response.data.data.list;
          this.pageable.totalCount = response.data.data.totalCount;
        })
      },
      reload() {
        let data = {
          pageSize: this.pageable.pageSize,
          pageNum: this.pageable.currentPage,
          key: this.formInline.key,
          name: this.formInline.name,
          close: this.formInline.hasHandUp
        };
        this.loadData(data);
      },
      onSubmit: function () {
        //重新加载数据
        var data = {
          pageSize: this.pageable.pageSize,
          pageNum: 1,
          key: this.formInline.key,
          name: this.formInline.name,
          close: this.formInline.hasHandUp
        };
        this.loadData(data);
        this.pageable.currentPage = 1;
      },
      handleSizeChange: function (val) {
        this.pageable.pageSize = val;
        this.pageable.currentPage = 1;
        //重新加载数据
        var data = {
          pageSize: val,
          pageNum: 1
        };
        this.loadData(data);
      },
      handleCurrentChange: function (val) {
        this.pageable.currentPage = val;
        //重新加载数据
        var data = {
          pageSize: this.pageable.pageSize,
          pageNum: val
        };
        this.loadData(data);
      },
      xmlUrl: function (id) {
        return "/resource/read?processDefinitionId=" + id + "&resourceType=xml";
      },
      imageUrl: function (id) {
        return "/resource/read?processDefinitionId=" + id + "&resourceType=image";
      },
      formatter: function (row, column) {
        return formatDate(new Date(row.deploymentDate), 'yyyy-MM-dd HH:mm:ss');
      },
      updateSuspendState: function (id, state) {
        let operation = 'suspend';
        if (state === true) {
          operation = 'active';
        }
        updateSuspendState(id, operation).then(response => {
          this.reload();
        })
      },
      deleteDeployment: function (id, name) {
        this.$confirm(`确定删除${name}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProcess(id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.reload();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      convertToModel: function (procId) {
        convertToModel(procId).then(response => {
          this.$message({
            type: 'success',
            message: '转换成功'
          });
        });
      },
      fillHttpHead(tenantId) {

      },
      processSetting: function (row) {
        this.centerDialogVisible = true;
        this.dialog.key = row.key;
        this.dialog.name = row.name;
        this.dialog.formServer = row.tenantId;
        this.fillHttpHead(row.tenantId);
        searchProcessExtendInfo(row.key).then(response => {
          this.dialog.approveType = response.data.data.approveType;
          this.dialog.formKey = response.data.data.formKey;
          this.dialog.autoJump = response.data.data.autoJump + '';
          this.dialog.boardType = response.data.data.boardType;
        })
      },
      doSetting: function (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              processDefinitionName: this.dialog.name,
              processDefinitionKey: this.dialog.key,
              formKey: this.dialog.formKey,
              autoJump: this.dialog.autoJump,
              approveType: this.dialog.approveType,
              boardType: this.dialog.boardType,
              formServer: this.dialog.formServer
            };
            saveProcessExtendInfo(data).then(response => {
              this.$notify({
                title: '消息',
                message: '保存成功',
                type: 'success'
              });
            });

            this.centerDialogVisible = false;
            this.$refs[formName].resetFields();
          } else {
            return false;
          }
        });
      },
      showNodeDialog: function (row) {
        this.nodeDialogVisible = true;
        this.selectedProcessKey = row.key;
        this.selectedProcessDefinedId = row.id;
        this.loadProcessNodeList(row.id)
      },
      loadProcessNodeList: function (id) {
        //加载节点信息
        loadNode(id).then(response => {
          this.processNodeList = response.data.data;
        })
      },
      qrySysOptionChange: function (value) {
        this.fillHttpHead(value);
      },
      loadTaskApproverSetting: function () {
        let data = {
          processKey: this.selectedProcessKey,
          taskKey: this.selectedTaskKey
        };
        loadTaskApproverSetting(data).then(response => {
          this.processNodeApproverList = response.data.data;
        });
      },
      approverSetting: function (row) {
        this.approveDialogVisible = true;
        this.selectedTaskKey = row.taskKey;
        this.loadTaskApproverSetting();
      },
      getApproverMap(type) {
        let map = new Map();
        this.processNodeApproverList.forEach((item, index) => {
          if (item.approverType === type) {
            map.set(item.value, item);
          }
        });

        return map;
      },
      roleCallback: function (val) {
        if (val.length > 0) {
          let map = this.getApproverMap(APPROVER_TYPE.ROLE);
          val.forEach((ele, index) => {
            //列表中不存在的角色加入进去
            if (!map.get(ele.roleCode)) {
              var roleObj = {
                approverType: APPROVER_TYPE.ROLE,
                value: ele.roleCode,
                description: ele.roleName
              };
              this.processNodeApproverList.push(roleObj);
            }
          })
        }
      },
      userCallBack: function (val) {
        if (val) {
          let map = this.getApproverMap(APPROVER_TYPE.USER_ID);
          if (!map.get(val.id)) {
            let roleObj = {
              approverType: APPROVER_TYPE.USER_ID,
              value: val.id,
              description: val.username
            };
            this.processNodeApproverList.push(roleObj);
          }

        }
      },
      unitCallBack: function (val) {
        if (val) {
          let map = this.getApproverMap(APPROVER_TYPE.DEPART_LEADER);
          val.forEach((unit, index) => {
            if (!map.get(unit.unitId)) {
              let unitObj = {
                approverType: APPROVER_TYPE.DEPART_LEADER,
                value: LEADER_TYPE.SPECIFIED_UNIT,
                unitCode: unit.unitId,
                description: "指定部门领导[" + unit.unitName + "]"
              };
              this.processNodeApproverList.push(unitObj);
            }
          });
        }
      },
      addRole: function () {
        this.$refs['choseRole'].changeVisiable();
      },
      addUser: function () {
        this.$refs['choseUser'].changeVisiable();
      },
      addUnit: function () {
        this.$refs['choseUnit'].changeVisiable();
      },
      addLeader: function (leaderType, description) {
        var _this = this;
        var companyLeaderObj = {
          approverType: APPROVER_TYPE.DEPART_LEADER,
          value: leaderType,
          description: description
        };
        var exist = false;
        $(_this.processNodeApproverList).each(function (idx, ele) {
          if (ele.approverType === APPROVER_TYPE.DEPART_LEADER && leaderType === ele.value) {
            exist = true;
          }
        });
        if (!exist) {
          _this.processNodeApproverList.push(companyLeaderObj);
        } else {
          _this.$message("记录已存在");
        }
      },
      addCompanyLeader: function () {
        // this.addLeader(LEADER_TYPE.COMPANY_LEADER, "分总");
      },
      addUnitLeader: function () {
        // this.addLeader(LEADER_TYPE.UNIT_LEADER, "部门领导");
      },
      addUntilCompanyLeader: function () {
        // this.addLeader(LEADER_TYPE.UNIT_LEADER_UNTIL_COMPANY_LEADER, "部门领导审批至分总");
      },
      addCustomDefine: function () {
        var _this = this;
        var companyLeaderObj = {
          approverType: APPROVER_TYPE.CUSTOM_DEFINE,
          description: "业务系统自定义"
        };
        var exist = false;
        $(_this.processNodeApproverList).each(function (idx, ele) {
          if (ele.approverType === APPROVER_TYPE.CUSTOM_DEFINE) {
            exist = true;
          }
        });
        if (!exist) {
          _this.processNodeApproverList.push(companyLeaderObj);
        } else {
          _this.$message("记录已存在");
        }
      },
      addTaskApprover: function () {
        let data = {
          processKey: this.selectedProcessKey,
          taskKey: this.selectedTaskKey,
          approverConfigList: this.processNodeApproverList
        };
        saveTaskApproverSetting(data).then(response => {
          this.$message({
            type: 'success',
            message: '添加成功'
          });
          this.approveDialogVisible = false;
          this.loadProcessNodeList(this.selectedProcessDefinedId);
        })
      },
      deleteRow(index, rows) {
        rows.splice(index, 1);
      },
      approverTypeFormatter(row, column) {
        return APPROVER_TYPE_NAME[row.approverType];
      }
    },
    created: function () {
      this.loadData();
    }
  }
</script>

<style scoped>
  .process-table-expand {
    font-size: 0;
  }

  .process-table-expand label {
    width: 80px;
    color: #99a9bf;
  }

  .process-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
